import { useSessionStorage } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import { i18n, langList, localeKey, defaultLanguage } from '@/locales';
import dayjs from 'dayjs';

export const useLocale = () => {
  const { locale } = useI18n({ useScope: 'global' });

  const changeLocale = (lang: string) => {
    // 如果切换的语言不在对应语言文件里则默认为简体中文
    if (langList.findIndex((item) => item.key === lang) === -1) {
      // eslint-disable-next-line no-param-reassign
      lang = defaultLanguage;
    }
    locale.value = lang;
    useSessionStorage(localeKey, defaultLanguage).value = lang;
  };

  const getComponentsLocale = computed(() => {
    return i18n.global.getLocaleMessage(locale.value).componentsLocale;
  });

  watch(
    locale,
    () => {
      document.querySelector('html')?.setAttribute('lang', locale.value);
      dayjs.locale(i18n.global.getLocaleMessage(locale.value).dayLocale);
    },
    {
      immediate: true,
    },
  );

  return {
    locale,
    changeLocale,
    getComponentsLocale,
  };
};
